package com.op.studyingliteapp.fragment.seminar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.op.studyingliteapp.R;
import com.op.studyingliteapp.activity.SendPostActivity;
import com.op.studyingliteapp.activity.sonseminar.sonSeminarActivity;
import com.op.studyingliteapp.bean.SeminarBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.common.SeminarsUrl;
import com.op.studyingliteapp.database.dao.SeminarDao;
import com.op.util.SharedPreferenceUtil;
import com.op.util.StringUtils;
import com.op.util.asynctask.HttpPostTask;
import com.op.util.asynctask.OnTaskProcessListener;
import com.op.util.pullrefresh.RefreshableView;
import com.op.util.pullrefresh.RefreshableView.PullToRefreshListener;

/**
 * by kim 2015.7.25//课程讨论
 */
public class SeminarFragment extends Fragment {
	private String getCourseId;
	private String getUserId;
	private final static String TAG = SeminarFragment.class.getSimpleName();
	ArrayList<SeminarData> discussion_List = new ArrayList<SeminarData>();
	private SeminarAdapter mAdapter;
	private SharedPreferences preferences;
	RefreshableView refreshableView;
	public static  ListView listviewSeminar;
	private View root;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		root = inflater.inflate(R.layout.fragment_seminar, container, false);
		preferences = getActivity().getSharedPreferences("StudyingLite",
				Context.MODE_PRIVATE);
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		getUserId = preferences.getString(Common.Prefs.USER_ID, "");
		downLoadData();
		setListView(root);

		refreshableView = (RefreshableView) root
				.findViewById(R.id.refreshable_view_seminar);
		refreshableView.setOnRefreshListener(new PullToRefreshListener() {

			@Override
			public void onRefresh() {
				try {
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
				/**
				 * 另起线程进行刷新
				 */
				Thread action = new Thread(new Runnable() {

					@Override
					public void run() {
						Looper.prepare();
						downLoadData();
						Looper.loop();
					}
				});
				action.start();
				refreshableView.finishRefreshing();
			}

		}, 123);
		
//		listviewSeminar.setOnItemLongClickListener(new OnItemLongClickListener() {
//
//			@Override
//			public boolean onItemLongClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				Toast.makeText(getActivity(), "123", Toast.LENGTH_SHORT).show();
//				return false;
//			}
//		});
		
		return root;
	}

	/*
	 * 设定listview
	 */
	private void setListView(View root) {

		 listviewSeminar = (ListView) root
				.findViewById(R.id.listviewSeminar);
		mAdapter = new SeminarAdapter(getActivity(), discussion_List);
		listviewSeminar.setAdapter(mAdapter);
		registerForContextMenu(listviewSeminar);
		listviewSeminar.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.SEMINAR_ID,
						mAdapter.getSeminarId(position));
				SharedPreferenceUtil.saveData(getActivity(), prefsMap);
				Intent intent = new Intent();
				intent.setClass(getActivity(), sonSeminarActivity.class);
				startActivity(intent);
			}
		});
	}
	
	

	/**
	 * 通过courseId从网上下拉主贴json，调用解析，和存入数据库再刷新界面
	 */
	public void downLoadData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("courseId", getCourseId));
		HttpPostTask task = new HttpPostTask(getActivity(),
				SeminarsUrl.GET_ROOT_SEMINARS_BY_COURSE_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					// 有网络登陆时
					analyticalSeminar(result);
					getDataFromDatabase();
				}
				mAdapter.notifyDataSetChanged();

			}

		});
		task.execute();// 执行结束，圈转完

	}

	/**
	 * 从数据库获取数据 // 从数据库提取课程讨论主贴内容
	 */
	public void getDataFromDatabase() {
		SeminarDao seminarDao = new SeminarDao(getActivity(), getUserId);
		List<SeminarBean> seminar = seminarDao
				.getSeminarByCourseId(getCourseId);
		discussion_List.clear();
		// 获取讨论标题
		for (int i = 0; i < seminar.size(); i++) {
			String title = seminar.get(i).getTitle();
			String time = seminar.get(i).getCreateTime();
			String context = seminar.get(i).getContent();
			String name = seminar.get(i).getUserBean().getName();
			String avatar = seminar.get(i).getUserBean().getImageUrl();
			String like = seminar.get(i).getLikeCount();// 点赞
			String ChildCount = seminar.get(i).getChildCount();// 评论数
			String image = seminar.get(i).getImageUrl();
			String userid = seminar.get(i).getUserBean().getId();
			String seminarId = seminar.get(i).getId();
			/*
			 * 依次是名字，头像,时间，点赞，评论次数,标题,内容,图片,用户id,seminarId,
			 */
			if (context.length() > 20) {
				context = context.substring(0, 19);
			}
			if (title.length() > 10) {
				title = title.substring(0, 10);
			}
			discussion_List.add(new SeminarData(name, avatar, context, like,
					ChildCount, title, time, image, userid, seminarId));
		}
	}

	/**
	 * 解析主贴或子贴json，并存入数据库
	 *
	 * @param result
	 */
	public void analyticalSeminar(String result) {

		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");
				// 不存在parent，即主贴时
				if (message.equals("Success")) {
					SeminarDao seminarDao = new SeminarDao(getActivity(),
							getUserId);
					// 清空数据库
					seminarDao.empty();
					JSONObject resultMap = jsonobjectresult
							.getJSONObject("resultMap");
					JSONArray seminarList = resultMap
							.getJSONArray("seminarList");
					for (int i = 0; i < seminarList.length(); i++) {
						JSONObject seminar = new JSONObject();
						seminar = seminarList.getJSONObject(i);

						// 将JsonObject存入本地数据库
						SeminarBean seminarBean = new SeminarBean();
						seminarBean.fillAttributeByJson(seminar);
						seminarDao.insertOrUpdate(seminarBean);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();

			}
		}
	}

	/**
	 * 删除网上数据库帖子方法
	 */
	public void deleteItem(String SeminarId, String Userid) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("seminarId", SeminarId));
		params.add(new BasicNameValuePair("userId", Userid));
		HttpPostTask task = new HttpPostTask(getActivity(),
				SeminarsUrl.DELETE_SEMINARS_BY_SEMINAR_ID_AND_USER_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {

			@Override
			public void prepare() {
				// TODO Auto-generated method stub

			}

			@Override
			public void completed(String result) {
				// TODO Auto-generated method stub

			}
		});
		mAdapter.notifyDataSetChanged();
		task.execute();
	}

	@Override
	public void onResume() {
		setHasOptionsMenu(true);
		// downLoadData();
		super.onResume();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		getActivity().getMenuInflater().inflate(R.menu.seminar_ctionbar, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.sendpost:
			Intent intent = new Intent(getActivity(), SendPostActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 长按弹出菜单
	 */
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		int index = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
		
		if (!RefreshableView.isPulling == false) {
			SeminarData data = (SeminarData) listviewSeminar.getItemAtPosition(index);
			if(getUserId.equals(data.getUserid())){
				menu.add(0, 0, 0, "删除");
				
			}
			menu.add(0, 1, 0, "收藏");
			menu.add(0, 2, 0, "举报");
			super.onCreateContextMenu(menu, v, menuInfo);
		
		}
		

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo;
		menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		int index = menuInfo.position;
		switch (item.getItemId()) {
		case 0:
			delete(index);
			break;
		case 1:
			Toast.makeText(getActivity(), "待开发", Toast.LENGTH_SHORT).show();
			break;
		case 2:
			Toast.makeText(getActivity(), "待开发", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	/**
	 * 删除帖子
	 * @param position
	 */
	private void delete(final int position) {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setMessage("确认删除帖子吗？");
		builder.setTitle("提示");
		builder.setNeutralButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SeminarData data = mAdapter.getItem(position);
				deleteItem(data.getSeminarId(), data.getUserid());
				discussion_List.remove(position);
				mAdapter.notifyDataSetChanged();
			}
		});
		builder.setNegativeButton("取消", null);
		builder.create();
		builder.show();
	}

}
